import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Drawer, message } from 'antd';
import React, { useRef, useState } from 'react';
import {
  addInterfaceInfoUsingPOST, deleteInterfaceInfoUsingPOST,
  listInterfaceInfoByPageUsingGET,
  offlineInterfaceInfoUsingPOST,
  onlineInterfaceInfoUsingPOST, updateInterfaceInfoUsingPOST,

} from "../../../services/yuapi-backend/interfaceInfoController";
import {SortOrder} from "antd/lib/table/interface";
import UpdateModal from "@/pages/Admin/InterfaceInfo/components/UpdateModal";
import CreateModal from './components/CreateModal';

/**
 * React.FC 类型的组件，相当于一个
 * React Function Component
 *
 * TableList 用于展示数据库表中的数据，
 * 也是对应了 UI 中某个表格组件的渲染和事件处理逻辑
 *  */
 const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>() ;
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);

  /**
   * 接下俩就是tablelist中增删改查以及上线线接口的---五个函数
   */

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  // 将添加节点的组件放到TableList中
  const handleAdd = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在添加');
    try {
      await addInterfaceInfoUsingPOST({
        ...fields
      });
      hide();
      message.success('创建成功');
      handleModalOpen(false);//创建成功关闭模态框
      return true;
    } catch (error : any) {
      hide();
      message.error('创建失败.' + error.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfo) => {
    if(!currentRow){
      return;
    }
    const hide = message.loading('修改中...');
    try {
      await updateInterfaceInfoUsingPOST({
        id: currentRow.id,
        ...fields,
      });
      hide();
      message.success('操作成功!');
      return true;
    } catch (error : any) {
      hide();
      message.error('操作失败.' + error.message);
      return false;
    }
  };

  /**
   *   《发布接口》
   *  删除节点与发布下线接口接收的参数都是id，所以直接复用
   *
   *
   * @param record
   */
  //record表示单行记录 类型是 IdRequest
  const handleOnline = async (record: API.IdRequest) => {
    const hide = message.loading('发布中');
    if (!record) return true;
    try {
      await onlineInterfaceInfoUsingPOST({
        id:record.id
      });
      hide();
      message.success('发布成功');
      actionRef.current?.reload();//actionRef可以拿到ProTable权限 实现页面刷新
      return true;
    } catch (error:any) {
      hide();
      message.error('发布失败.' + error.message);
      return false;
    }
  };

  /**
   *   《下线接口》
   *  删除节点与发布下线接口接收的参数都是id，所以直接复用
   *
   *
   * @param selectedRows
   */
    //record表示单行记录 类型是 IdRequest
  const handleOffline = async (record: API.IdRequest) => {
      const hide = message.loading('下线中');
      if (!record) return true;
      try {
        await offlineInterfaceInfoUsingPOST({
          id:record.id
        });
        hide();
        message.success('下线成功');
        actionRef.current?.reload();//actionRef可以拿到ProTable权限 实现页面刷新
        return true;
      } catch (error:any) {
        hide();
        message.error('下线失败.' + error.message);
        return false;
      }
    };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param record
   */
  const handleRemove = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteInterfaceInfoUsingPOST({
        id: record.id
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };


// 写一次表单想要哪些列，之后直接调用此API
  // @ts-ignore
  const columns: ProColumns<API.InterfaceInfo>[] = [
    // {
    //   title: 'id',
    //   dataIndex: 'id',
    //   valueType:'index',
    // },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType:'text',
      //不向后台发送请求 直接校验
      formItemProps:{
        rules:[{
          required:true,
          // message:'此处不可为空', 不写此处会有默认提示
        }]
      }
    },
    {
      title: '描述',
      dataIndex: 'desc',
      valueType: 'textarea',
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
    },
    {
      title: 'url',
      dataIndex: '接口地址',
      valueType: 'text',
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      valueType: 'jsonCode',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm:true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm:true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',

      // record即为当前记录
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,

        record.status === 0 ? <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            handleOnline(record);
          }}
        >
          发布
        </a> : null,

        record.status === 1 ? <Button
          type="text"
          key="config"
          danger
          onClick={() => {

            handleOffline(record);
          }}
        >
          下线
        </Button> : null,

        <Button
          type="text"
          key="config"
          danger
          onClick={() => {
             handleRemove(record);
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表单'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}

// 请求 获取接口信息
        request={async(params ,sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) =>{
          const res: any = await listInterfaceInfoByPageUsingGET({
              ...params
            })
            if(res?.data){
               return {
                 data:res?.data.records || [],
                 success:true,
                 total: res?.data.total || 0,
               }
            }else{}
                return {
                  data: [],
                  success:false,
                  total: 0,
                }

         }}

        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />


      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}




      <UpdateModal
        columns = {columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible = {updateModalOpen}
        values={currentRow || {}}
       />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
        <CreateModal columns={columns} onCancel={()=>{handleModalOpen(false)}} onSubmit={(values)=>{handleAdd(values)}} visible={createModalOpen}/>
    </PageContainer>
  );
};

 export default TableList;


